package com.groupscore.score.controller;

import com.groupscore.score.pojo.Option;
import com.groupscore.score.pojo.Personal;
import com.groupscore.score.pojo.PersonalScore;
import com.groupscore.score.pojo.Score;
import com.groupscore.score.pojogroup.GroupScore;
import com.groupscore.score.pojogroup.OptionScore;
import com.groupscore.score.pojogroup.PersonalOptionScore;
import com.groupscore.score.service.LotterService;
import com.groupscore.score.service.PersonalScoreService;
import com.groupscore.score.service.ScoreService;
import com.groupscore.score.service.TeamService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/score")
public class ScoreController {

    @Autowired
    private ScoreService scoreService;
    @Autowired
    private PersonalScoreService personalScoreService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TeamService teamService;

    @Autowired
    private LotterService lotterService;

    /**
     * 小组抽签
     * @return
     */
    @PostMapping(value = "/teamdraw")
    @CrossOrigin
    public Result teamdraw(){

        return  new Result(true, StatusCode.OK, "小组抽签成功",teamService.findSearchTeam());
    }

    /**
     * 个人抽签(小组)
     * @return
     */
    @GetMapping(value = "/persondraw")
    @CrossOrigin
    public Result persondraw(){
        return  new Result(true, StatusCode.OK, "抽签成功！",lotterService.findSearchPerson());
    }


    /**
     * 个人抽签(单抽)
     * @return
     */
    @GetMapping(value = "/singledraw")
    @CrossOrigin
    public Result singledraw(){
        return  new Result(true, StatusCode.OK, "抽签成功！",lotterService.findSearchSingle());
    }

    /**
     * 个人抽签-确定
     * @return
     */
    @GetMapping(value = "/updateMemberFlag")
    @CrossOrigin
    public Result updateMemberFlag(String userId, String token){

        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {
            //判断是管理员
            if("admin".equals( claims.get( "roles" ) )) {
                lotterService.updateMember(userId);
            } else{
                return   new Result(false, StatusCode.ACCESSERROR,"无权访问");
            }
        }
        return  new Result(true, StatusCode.OK, "确定成功！",null);
    }
    /**
     * 打分
     */
     @PostMapping
     @CrossOrigin
     public Result add(@RequestBody GroupScore groupScore){
         System.out.println(groupScore.getToken());
        Claims claims = jwtUtil.parseJWT(groupScore.getToken());
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }
        //从redis中取出该用户对某个组,某一项的打分缓存
        for(Score os : groupScore.getScoreList()){
            if(redisTemplate.opsForValue().get("groupScore_"+claims.get("jti")+"_"+os.getOptionId()+"_"+groupScore.getGroupId()) != null){
                return new Result(false,StatusCode.REPERROR,"你已经给"+groupScore.getGroupId()+"组打过分了");
            }
            os.setGroupId(groupScore.getGroupId());
        }
        scoreService.add(groupScore.getScoreList(),claims.get("jti") + "");
        for(Score os : groupScore.getScoreList()){
            redisTemplate.opsForValue().set("groupScore_"+claims.get("jti")+"_"+os.getOptionId()+"_"+groupScore.getGroupId(),"1", 1, TimeUnit.DAYS);
        }
        return new Result(true, StatusCode.OK, "打分成功");
    }

    /**
     * 打分
     */
    @PostMapping
    @RequestMapping("/addPersonalScore")
    @CrossOrigin
    public Result addPersonalScore(@RequestBody PersonalOptionScore personalOptionScore){

        //jwt解析token,从中获取出用户id
        Claims claims = jwtUtil.parseJWT(personalOptionScore.getToken());
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }

        //从redis中取出该用户对某个组,某一项的打分缓存
        for(PersonalScore ps : personalOptionScore.getPersonalScoreList()){
            if(redisTemplate.opsForValue().get("personalScore_"+claims.get("jti")+"_"+ps.getOptionId()+"_"+personalOptionScore.getPersonalName()) != null){
                return new Result(false,StatusCode.REPERROR,"你已经给"+personalOptionScore.getPersonalName()+"打过分了");
            }
            ps.setPersonalName(personalOptionScore.getPersonalName());
        }

        //根据用户name查询用户
        personalScoreService.addPersonalScore(personalOptionScore.getPersonalScoreList(),claims.get("jti") + "");
        for(PersonalScore ps : personalOptionScore.getPersonalScoreList()){
            redisTemplate.opsForValue().set("personalScore_"+claims.get("jti")+"_"+ps.getOptionId()+"_"+personalOptionScore.getPersonalName(),"1", 1, TimeUnit.DAYS);
        }

        return new Result(true, StatusCode.OK, "打分成功");
    }

    /**
     * 查询小组得分,高到低
     */
    @GetMapping
    @CrossOrigin
    public Result groupScore(){
        return  new Result(true, StatusCode.OK, "查询成功",scoreService.groupScore());
    }

    /**
     * 查询小组中我的打分
     * @param userId
     * @return
     */
    @RequestMapping("/groupScoreByUserId")
    public Result groupScoreByUserId(String userId){
        return  new Result(true, StatusCode.OK, "查询成功",scoreService.groupScoreByUserId(request.getAttribute("userId")+""));
    }

    /**
     * 查询个人中我的打分
     * @param userId
     * @return
     */
    @RequestMapping("/personalScoreByUserId")
    public Result personalScoreByUserId(String userId){
        return  new Result(true, StatusCode.OK, "查询成功",personalScoreService.personalScoreByUserId(request.getAttribute("userId")+""));
    }

    @RequestMapping("/findScoresByUserId")
    @CrossOrigin
    public Result findScoresByUserId(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {
            return new Result(true,StatusCode.OK,"返回消息",scoreService.groupScoreByUserId(claims.get("jti")+""));
        }
        return new Result(false, StatusCode.ACCESSERROR,"无权访问");

    }

    @RequestMapping("/personalScoresByUser")
    @CrossOrigin
    public Result personalScoresByUser(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {

            return new Result(true,StatusCode.OK,"返回消息",personalScoreService.personalScoreByUserId(claims.get("jti")+""));
        }
        return new Result(false, StatusCode.ACCESSERROR,"无权访问");

    }

    /**
     * 查询个人得分,高到低
     */
    @GetMapping
    @RequestMapping("/personalScore")
    @CrossOrigin
    public Result personalScore(){
        return  new Result(true, StatusCode.OK, "查询成功",personalScoreService.personalScore());
    }
    /**
     * 查询小组全部打分
     */
    @GetMapping
    @RequestMapping("/allScore")
    @CrossOrigin
    public Result allScore(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {
            return new Result(true,StatusCode.OK,"返回消息",scoreService.allScore());
        }
        return new Result(false, StatusCode.ACCESSERROR,"无权访问");
    }
    /**
     * 查询个人全部打分
     */
    @GetMapping
    @RequestMapping("/allPersonalScore")
    @CrossOrigin
    public Result allPersonalScore(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {
            return new Result(true,StatusCode.OK,"返回消息",scoreService.allPersonalScore());
        }
        return new Result(false, StatusCode.ACCESSERROR,"无权访问");
    }


  /**
   * 查询全部选项
   * @return
   */
  @CrossOrigin
  @RequestMapping("/findOption")
  public Result findOption(){
    List<Map> optionMap=scoreService.findOption();
    System.out.println(optionMap);
    return new Result(true,StatusCode.OK,"查询成功",optionMap);
  }

  /**
   * 根据ID查询
   * @param id ID
   * @return
   */
  @CrossOrigin
  @RequestMapping("/findById/{id}")
  public Result findById(@PathVariable String id){
    return new Result(true,StatusCode.OK,"查询成功",scoreService.findById(id));
  }


  /**
   * 增加
   * @param
   */
  @CrossOrigin
  @RequestMapping("/addOption")
  public Result addOption(@RequestBody Option option  ){
    scoreService.addOption(option);
    return new Result(true,StatusCode.OK,"增加成功");
  }


  /**
   * 删除
   * @param id
   */
  @CrossOrigin
  @RequestMapping(value="/{id}" ,method = RequestMethod.DELETE)
  public Result deleteOption(@PathVariable String id ){
    scoreService.deleteOption(id);
    return new Result(true,StatusCode.OK,"删除成功");
  }


  /**
   * 修改
   * @param option
   */
  @CrossOrigin
  @RequestMapping(value = "/updateOption/{id}",method = RequestMethod.PUT)
  public Result updateOption(@RequestBody Option option, @PathVariable String id ){
    option.setId(id);
    scoreService.updateOption(option);
    return new Result(true, StatusCode.OK,"修改成功");
  }

    /**
     * 个人参赛名单保存
     */
    @PostMapping
    @RequestMapping("/savePersonal")
    @CrossOrigin
    public Result savePersonal(@RequestBody List<Personal> personalList){

        scoreService.savePersonal(personalList);
        return new Result(true, StatusCode.OK,"保存成功");
    }

    /**
     * 查询个人比赛名单
     */
    @CrossOrigin
    @RequestMapping("personalList")
    @GetMapping
    public Result personalList(){
        return new Result(true, StatusCode.OK,"查询成功",scoreService.personalList());
    }
}
